import doDelDataClick from '@/api/common/delDataApi'
import notBlankIdApi from '@/api/common/notBlankIdApi'
import userInsertOrUpdateApi from '@/api/user/userInsertOrUpdateApi'
import userPageApi from '@/api/user/userPageApi'
import userResetAvatarApi from '@/api/user/userResetAvatarApi'
import { checkIdSet } from '@/components/CAddOrderNo/CAddOrderNo'
import CSearchForm from '@/components/CSearchForm/CSearchForm'
import CTable from '@/components/CTable/CTable'
import IUserInsertOrUpdateForm from '@/model/form/user/IUserInsertOrUpdateForm'
import IUserPageForm from '@/model/form/user/IUserPageForm'
import IUserInfoByIdVO from '@/model/vo/user/IUserInfoByIdVO'
import IUserPageVO from '@/model/vo/user/IUserPageVO'
import { useAppSelector } from '@/store'
import {
  execConfirm,
  onModalCancel,
  ToastError,
  ToastSuccess,
} from '@/util/CommonUtil'
import { passwordRSAEncrypt, RSAEncryptPro } from '@/util/UserUtil'
import { IconChevronDown, IconRefresh, IconSearch } from '@douyinfe/semi-icons'
import {
  Badge,
  Button,
  ButtonGroup,
  Dropdown,
  Form,
  Modal,
  Row,
  Space,
} from '@douyinfe/semi-ui'
import { FormApi } from '@douyinfe/semi-ui/lib/es/form'
import { ChangeInfoSorter } from '@douyinfe/semi-ui/lib/es/table'
import {
  Dispatch,
  MutableRefObject,
  SetStateAction,
  useEffect,
  useRef,
  useState,
} from 'react'
import UserColumns from './UserColumns'
import UserFormItem, { getUserFormSelectData } from './UserFormItem'
import UserSearchFormItem from './UserSearchFormItem'
import UserUpdatePassword from './UserUpdatePassword'

export default function User() {
  const [selectedRowKeyList, setSelectedRowKeyList] = useState<
    (string | number)[]
  >([]) // 表格选中的 key集合
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState<IUserPageVO[]>([])
  const [initForm, setInitForm] = useState<IUserInsertOrUpdateForm>({}) // modal表单初始值
  const [modalTitle, setModalTitle] = useState('')
  const [modalVisible, setModalVisible] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false) // modal确认按钮的 loading状态
  const [sideSheetVisible, setSideSheetVisible] = useState(false) // 搜索 sideSheet是否显示
  const [searchForm, setSearchForm] = useState<IUserPageForm>({}) // 搜索表单初始值

  const [total, setTotal] = useState(0)
  const [pageNum, setPageNum] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [sorter, setSorter] = useState<ChangeInfoSorter<any>>()

  const formApi = useRef<FormApi>()

  const [updatePasswordModalVisible, setUpdatePasswordModalVisible] =
    useState(false) // 修改密码 modal
  const [userUpdatePasswordIdSet, setUserUpdatePasswordIdSet] = useState<
    string[]
  >([])

  // 监听 updatePasswordModalVisible，如果为 false，则重置 userUpdatePasswordIdSet
  useEffect(() => {
    if (updatePasswordModalVisible === false) {
      setUserUpdatePasswordIdSet([])
    }
  }, [updatePasswordModalVisible])

  const rsaPublicKey = useAppSelector((state) => state.common.rsaPublicKey)

  // 执行获取 table数据
  function doGetTableData() {
    getTableData(
      setDataSource,
      setLoading,
      searchForm,
      pageNum,
      pageSize,
      setTotal,
      sorter
    )
  }

  useEffect(() => {
    doGetTableData()
  }, [])

  const { roleList, deptList, jobList } = getUserFormSelectData(modalVisible)

  return (
    <div className="p-l-r-20">
      <CSearchForm
        sideSheetVisible={sideSheetVisible}
        setSideSheetVisible={setSideSheetVisible}
        getTableData={(values: any) => {
          setPageNum(1) // 这里的值不会立即生效
          setPageSize(10) // 这里的值不会立即生效
          getTableData(
            setDataSource,
            setLoading,
            values,
            1,
            10,
            setTotal,
            sorter
          )
        }}
        setSearchForm={setSearchForm}
      >
        <UserSearchFormItem></UserSearchFormItem>
      </CSearchForm>

      <Modal
        title={modalTitle}
        visible={modalVisible}
        onOk={() => {
          formApi.current?.submitForm()
        }}
        onCancel={() => {
          onModalCancel(setModalVisible, formApi.current, initForm)
        }}
        maskClosable={false}
        confirmLoading={confirmLoading}
        width={800}
      >
        <Form
          onSubmit={(form) => {
            if (confirmLoading) return
            modalSubmitClick(
              form,
              setConfirmLoading,
              setModalVisible,
              doGetTableData,
              rsaPublicKey
            )
          }}
          disabled={confirmLoading}
          getFormApi={(api) => (formApi.current = api)}
          initValues={initForm}
        >
          <Row gutter={30}>
            <UserFormItem
              roleList={roleList}
              deptList={deptList}
              jobList={jobList}
              confirmLoading={confirmLoading}
            />
          </Row>
        </Form>
      </Modal>

      <div className="flex jc-sb m-t-b-10">
        <Space>
          <Button
            theme="solid"
            onClick={() => {
              const initFormTemp: IUserInsertOrUpdateForm = {
                enableFlag: true,
              }
              setInitForm(initFormTemp)
              setModalTitle('新增用户')
              setModalVisible(true)
            }}
          >
            新增
          </Button>
          <Button
            theme="solid"
            type="danger"
            onClick={() => {
              delData(selectedRowKeyList, setSelectedRowKeyList, doGetTableData)
            }}
          >
            注销
          </Button>
          <Dropdown
            clickToHide
            stopPropagation
            render={
              <Dropdown.Menu>
                <Dropdown.Item
                  onClick={() => {
                    if (!checkIdSet(selectedRowKeyList)) {
                      return
                    }
                    resetAvatarClick(doGetTableData, selectedRowKeyList)
                  }}
                >
                  重置头像
                </Dropdown.Item>
                <Dropdown.Item
                  onClick={() => {
                    if (!checkIdSet(selectedRowKeyList)) {
                      return
                    }
                    setUserUpdatePasswordIdSet(selectedRowKeyList as string[])
                    setUpdatePasswordModalVisible(true)
                  }}
                >
                  修改密码
                </Dropdown.Item>
              </Dropdown.Menu>
            }
          >
            <Button
              type="tertiary"
              iconPosition="right"
              icon={<IconChevronDown />}
            >
              更多操作
            </Button>
          </Dropdown>
        </Space>

        {/* @ts-ignore */}
        <ButtonGroup>
          <Button
            onClick={() => {
              setSideSheetVisible(true)
            }}
            icon={
              <Badge dot={Object.keys(searchForm).length !== 0} type="warning">
                <IconSearch title="搜索" className="flex ai-c" />
              </Badge>
            }
          ></Button>
          <Button
            onClick={() => {
              if (!loading) {
                doGetTableData()
              }
            }}
            disabled={loading}
            icon={<IconRefresh spin={loading} title="刷新" />}
          ></Button>
        </ButtonGroup>
      </div>

      <CTable<IUserPageVO>
        onChange={({ sorter }) => {
          setSorter(sorter)
          getTableData(
            setDataSource,
            setLoading,
            searchForm,
            pageNum,
            pageSize,
            setTotal,
            sorter
          )
        }}
        columns={UserColumns}
        dataSource={dataSource}
        loading={loading}
        selectedRowKeyList={selectedRowKeyList}
        setSelectedRowKeyList={setSelectedRowKeyList}
        pagination={{
          total,
          currentPage: pageNum,
          pageSize,
          onChange: (currentPage: number, pageSize: number) => {
            setPageNum(currentPage) // 这里的值不会立即生效
            setPageSize(pageSize) // 这里的值不会立即生效
            getTableData(
              setDataSource,
              setLoading,
              searchForm,
              currentPage,
              pageSize,
              setTotal,
              sorter
            )
          },
          showSizeChanger: true,
        }}
        defaultOperateClickFun={(text, record, index) => {
          editData(
            setInitForm,
            setModalTitle,
            setModalVisible,
            setConfirmLoading,
            record,
            formApi,
            confirmLoading
          )
        }}
        operateDropdownItem={(text, record, index) => (
          <>
            <Dropdown.Item
              onClick={() => {
                editData(
                  setInitForm,
                  setModalTitle,
                  setModalVisible,
                  setConfirmLoading,
                  record,
                  formApi,
                  confirmLoading
                )
              }}
            >
              编辑
            </Dropdown.Item>
            <Dropdown.Item
              onClick={() => {
                resetAvatarClick(doGetTableData, [record.id])
              }}
            >
              重置头像
            </Dropdown.Item>
            <Dropdown.Item
              onClick={() => {
                setUserUpdatePasswordIdSet([record.id])
                setUpdatePasswordModalVisible(true)
              }}
            >
              修改密码
            </Dropdown.Item>
            <Dropdown.Item
              className="red"
              onClick={() => {
                delData(
                  selectedRowKeyList,
                  setSelectedRowKeyList,
                  doGetTableData,
                  record
                )
              }}
            >
              注销
            </Dropdown.Item>
          </>
        )}
      ></CTable>

      <UserUpdatePassword
        idSet={userUpdatePasswordIdSet}
        modalVisible={updatePasswordModalVisible}
        setModalVisible={setUpdatePasswordModalVisible}
      ></UserUpdatePassword>
    </div>
  )
}

// 编辑数据
function editData(
  setInitForm: Dispatch<SetStateAction<IUserInsertOrUpdateForm>>,
  setModalTitle: Dispatch<SetStateAction<string>>,
  setModalVisible: Dispatch<SetStateAction<boolean>>,
  setConfirmLoading: Dispatch<SetStateAction<boolean>>,
  record: IUserPageVO,
  formApi: MutableRefObject<FormApi<any> | undefined>,
  confirmLoading: boolean
) {
  if (confirmLoading) {
    return
  }
  setInitForm({ id: record.id }) // 重置 initForm的值
  setModalTitle('编辑用户')
  setModalVisible(true)
  setConfirmLoading(true)
  notBlankIdApi<IUserInfoByIdVO>('/user/infoById', { id: record.id }).then(
    ({ data }) => {
      setInitForm(data.data)
      formApi.current?.setValues(data.data, { isOverride: true })
      setConfirmLoading(false)
    }
  )
}

// 获取 table数据
function getTableData(
  setDataSource: Dispatch<SetStateAction<IUserPageVO[]>>,
  setLoading: Dispatch<SetStateAction<boolean>>,
  searchForm: IUserPageForm,
  pageNum: number,
  pageSize: number,
  setTotal: Dispatch<SetStateAction<number>>,
  sorter: ChangeInfoSorter<any> | undefined
) {
  setLoading(true)
  userPageApi({
    ...searchForm,
    pageNum,
    pageSize,
    orderList: sorter?.sortOrder
      ? [{ name: sorter.dataIndex, value: sorter.sortOrder }]
      : [],
  })
    .then(({ data }) => {
      setDataSource(data.data.records)
      setTotal(data.data.total)
      setLoading(false)
    })
    .catch(() => {
      setLoading(false)
    })
}

// 删除数据
function delData(
  selectedRowKeyList: (string | number)[],
  setSelectedRowKeyList: Dispatch<SetStateAction<(string | number)[]>>,
  getTableData: () => void,
  record?: IUserPageVO
) {
  doDelDataClick(
    '/user/deleteByIdSet',
    selectedRowKeyList,
    setSelectedRowKeyList,
    getTableData,
    record,
    record?.nickname,
    '注销'
  )
}

// modal，表单提交事件
function modalSubmitClick(
  form: IUserInsertOrUpdateForm,
  setConfirmLoading: Dispatch<SetStateAction<boolean>>,
  setModalVisible: Dispatch<SetStateAction<boolean>>,
  doGetTableData: () => void,
  rsaPublicKey: string
) {
  if (!form.email) {
    form.email = undefined
  }
  if (!form.phone) {
    form.phone = undefined
  }
  if (!form.email && !form.phone) {
    ToastError('邮箱和手机号必填一个')
    return
  }

  setConfirmLoading(true)

  const date = new Date()
  form.origPassword = RSAEncryptPro(form.password!, rsaPublicKey, date)
  form.password = passwordRSAEncrypt(form.password!, rsaPublicKey, date)

  userInsertOrUpdateApi(form)
    .then(({ data }) => {
      setModalVisible(false)
      setConfirmLoading(false)
      ToastSuccess(data.msg)
      doGetTableData() // 刷新table
    })
    .catch(() => {
      setConfirmLoading(false)
    })
}

// 点击【重置头像】
function resetAvatarClick(
  doGetTableData: () => void,
  selectedRowKeyList: (string | number)[]
) {
  execConfirm(
    () => {
      return userResetAvatarApi({ idSet: selectedRowKeyList }).then(
        ({ data }) => {
          ToastSuccess(data.msg)
          doGetTableData()
        }
      )
    },
    undefined,
    '确定重置头像？'
  )
}
